package com.aaa.ssm.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Configuration
public class MyIntercepterConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(
                        new HandlerInterceptor() {
                            @Override
                            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                                String method = request.getMethod();
                                if(method.equals("OPTIONS")){
                                    return true;
                                }
                                Object emp = request.getSession().getAttribute("emp");

                                if(emp == null){
                                    response.setContentType("text/json;charset=utf-8");
                                    PrintWriter out = response.getWriter();
                                    out.write("{'msg':'sorry must login'}");

                                    return false;
                                }
                                return true;
                            }
                        }
                ).order(1).addPathPatterns("/**")
                .excludePathPatterns( "/doc.html", "/webjars/**", "/swagger-resources/**", "/v2/api-docs")

                .excludePathPatterns("/emp")
                .excludePathPatterns("/*.jpg","/*.jpeg","/*.png","/*.g1f","/*.css","/*.s","/*.html","/*.ico")
                .excludePathPatterns("/emp/login").excludePathPatterns("/upload");
    }
}